package models

import (
	"github.com/beego/beego/v2/client/orm"
)

type BackendUserQueryParam struct {
	BaseQueryParam
	UserNameLike string //模糊查询
	RealNameLike string //模糊查询
	Mobile       string //精确查询
	SearchStatus string //为空不查询，有值精确查询
	Filter       string
}

type BackendUser struct {
	Id                   int
	RealName             string `orm:"size(32)"`
	UserName             string `orm:"size(24)"`
	UserPwd              string `json:"-"`
	IsSuper              bool
	Status               int
	Mobile               string `orm:"size(16)"`
	Email                string `orm:"size(256)"`
	Avatar               string `orm:"size(256)"`
	DepartmentId         int64  //隶属部门
	ExtendDepartment     string // 扩展部门
	ExtendDepartmentList []string              `orm:"-" json:""`
	FormExtendDepartment []int                 `orm:"-" form:"ExtendDepartment" json:""` // 接收扩展部门
	RoleIds              []int                 `orm:"-" form:"RoleIds"`
	RoleBackendUserRel   []*RoleBackendUserRel `orm:"reverse(many)"` // 设置一对多的反向关系
	ResourceUrlForList   []string              `orm:"-"`
}

func (a *BackendUser) TableName() string {
	return BackendUserTBName()
}

//按部门获取后台用户
func GetDepBackendUsers(dep int64) []*BackendUser {
	data := make([]*BackendUser, 0)
	query := orm.NewOrm().QueryTable(BackendUserTBName())
	query.Filter("department_id", dep).Filter("status", 1).All(&data)
	return data
}

//获取分页数据
func BackendUserPageList(params *BackendUserQueryParam) ([]*BackendUser, int64) {
	query := orm.NewOrm().QueryTable(BackendUserTBName())
	data := make([]*BackendUser, 0)
	//默认排序
	sortorder := "Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	cond := orm.NewCondition()
	if len(params.Filter) > 0 {
		cond = cond.Or("user_name__contains", params.Filter).Or("real_name__contains", params.Filter)
	}
	query = query.SetCond(cond)

	if len(params.Mobile) > 0 {
		query = query.Filter("mobile", params.Mobile)
	}
	if len(params.SearchStatus) > 0 {
		query = query.Filter("status", params.SearchStatus)
	}

	total, _ := query.Count()
	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)
	return data, total
}

// 根据id获取单条
func BackendUserOne(id int) (*BackendUser, error) {
	o := orm.NewOrm()
	m := BackendUser{Id: id}
	err := o.Read(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}

// 根据用户名密码获取单条
func BackendUserOneByUserName(username, userpwd string) (*BackendUser, error) {
	m := BackendUser{}
	err := orm.NewOrm().QueryTable(BackendUserTBName()).Filter("username", username).Filter("userpwd", userpwd).One(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}
